package com.soilflow.info.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soilflow.common.annotation.DataScope;
import com.soilflow.common.domain.LandNews;
import com.soilflow.common.domain.LandNotice;
import com.soilflow.common.domain.dto.LandNewsDto;
import com.soilflow.common.domain.vo.LandNewsVo;
import com.soilflow.common.mybatisplus.BaseEntity;
import com.soilflow.common.utils.StringUtils;
import com.soilflow.info.mapper.LandNewsMapper;
import com.soilflow.info.service.LandNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class LandNewsServiceImpl extends ServiceImpl<LandNewsMapper, LandNews> implements LandNewsService {

    @Resource
    private LandNewsMapper landNewsMapper;


    @DataScope(deptAlias = "ln")
    @Override
    public List<LandNewsVo> landNewsList(LandNewsDto dto) {
        return landNewsMapper.landNewsList(dto);
    }

    @Override
    public Boolean addNewNotice(LandNewsDto dto) {
        //1 查询新闻信息
        LambdaQueryWrapper<LandNews> query = new LambdaQueryWrapper<>();
        query.eq(StringUtils.isNotEmpty(dto.getNewsTitle()),LandNews::getNewsTitle,dto.getNewsTitle()).last("limit 1");

        if (ObjectUtils.isEmpty(landNewsMapper.selectOne(query))){
            LandNews landNotice = new LandNews();
            BeanUtils.copyProperties(dto,landNotice);
            landNewsMapper.insert(landNotice);
            return true;
        }

        return false;
    }

    @Override
    public LandNewsVo getLandNewsById(Long id) {
        LandNewsVo landNewsVo = new LandNewsVo();
        LandNews landNews = landNewsMapper.selectById(id);

        System.out.println(landNews);
        BeanUtils.copyProperties(landNews,landNewsVo);
        //格式化新闻日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String newsTime = sdf.format(landNews.getCreateTime());
        landNewsVo.setNewsTime(newsTime);

        //更新点击次数
        landNewsMapper.updateClickNum(id);
        return landNewsVo;
    }

    @Override
    public void updateLandNews(LandNewsDto dto) {
        LandNews landNews = new LandNews();
        BeanUtils.copyProperties(dto,landNews);
        landNews.setId(dto.getId());
        landNewsMapper.updateById(landNews);
    }

    /**
     * 前台新闻
     * @param dto
     * @return
     */
    @Override
    public List<LandNewsVo> newsList(LandNewsDto dto) {
        return landNewsMapper.landNewsList(dto);
    }

    @Override
    public List<LandNewsVo> landList(LandNewsDto dto) {
        return landNewsMapper.landList(dto);
    }
}
